﻿namespace Foundation.Core
{
    public interface ISelectExtend
    {
        void Set(string key, object value);

        object Get(string key);

        bool IsExists(string key);

        bool TryGetValue<T>(string key, out T value);

        bool Remove(string key);

        void Clear();
    }

    public class SelectExtend : ISelectExtend
    {
        public SelectExtend()
        {
        }

        public SelectExtend(IDictionary<string, object> dict)
        {
            Extensions = dict;
        }

        [System.Text.Json.Serialization.JsonExtensionData, Newtonsoft.Json.JsonExtensionData(WriteData = true)]
        protected internal virtual IDictionary<string, object> Extensions { get; set; }

        /// <summary>
        /// 扩展字典是否已实例化
        /// </summary>
        protected bool IsExtCreated => Extensions != null;

        public object Get(string key)
        {
            TryGetValue(key, out object value);

            return value;
        }

        public bool IsExists(string key)
        {
            throw new System.NotImplementedException();
        }

        public bool Remove(string key)
        {
            if (IsExtCreated)
            {
                return Extensions.Remove(key);
            }

            return false;
        }

        public virtual void Set(string key, object value)
        {
            if (Extensions == null)
            {
                Extensions = new Dictionary<string, object>();
            }

            Extensions[key] = value;
        }

        public bool TryGetValue<T>(string key, out T value)
        {
            value = default;
            if (IsExtCreated && Extensions.TryGetValue(key, out object objectValue))
            {
                if (objectValue != null)
                {
                    value = (T)objectValue;
                }

                return true;
            }

            return false;
        }

        public void Clear()
        {
            if (IsExtCreated)
            {
                Extensions.Clear();
            }
        }
    }
}
